package com.tuanzhang.mall.goods.application.impl;

import com.google.common.eventbus.EventBus;
import com.tuanzhang.mall.goods.application.SpuApplicationService;
import com.tuanzhang.mall.goods.domain.aggregate.Spu;
import com.tuanzhang.mall.goods.domain.event.SpuRecommendedEvent;
import com.tuanzhang.mall.goods.domain.factory.SpuFactory;
import com.tuanzhang.mall.goods.domain.service.SpuService;
import com.tuanzhang.mall.goods.domain.valueobj.SpuCode;
import com.tuanzhang.mall.goods.infrastructure.repository.SpuRepository;
import com.tuanzhang.mall.goods.types.req.SpuSaveParam;
import com.tuanzhang.mall.goods.types.req.UserApiVO;
import com.tuanzhang.mall.seller.types.exception.ApiException;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

/**
 * 类功能描述
 *
 * @author wangyl
 * @date 2025/6/17
 */
@Service
public class SpuApplicationServiceImpl implements SpuApplicationService {

    private final SpuRepository spuRepository;
    private final SpuService spuService;
    private final EventBus eventBus;

    public SpuApplicationServiceImpl(@Qualifier("mockSpuRepository") SpuRepository spuRepository, SpuService spuService, EventBus eventBus) {
        this.spuRepository = spuRepository;
        this.spuService = spuService;
        this.eventBus = eventBus;
    }

    /**
     * 添加商品
     *
     * @param param
     * @param userApiVO
     */
    @Override
    public void addSpu(SpuSaveParam param, UserApiVO userApiVO) {
        Spu spu = SpuFactory.createSpuFromParam(param, userApiVO);
        spuRepository.save(spu);
    }

    /**
     * 用户推荐商品
     *
     * @param spuCode
     */
    @Override
    public void recommend(Long spuCode) {
        Spu spu = spuRepository.findBySpuCode(SpuCode.getSpuCode(spuCode));
        if (null == spu) {
            throw new ApiException("参数异常");
        }
        Spu recommend = spuService.recommend(spu);
        spuRepository.update(recommend);
        //发布事件
        eventBus.post(new SpuRecommendedEvent(spu.getSpuCode()));
    }
}
